package com.heima.homeservicemanagementsystem.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.heima.homeservicemanagementsystem.config.WxConstants;
import com.heima.homeservicemanagementsystem.config.annotation.RestControllerMapping;
import com.heima.homeservicemanagementsystem.entity.SysUser;
import com.heima.homeservicemanagementsystem.entity.WxRTVO;
import com.heima.homeservicemanagementsystem.entity.WxUser;
import com.heima.homeservicemanagementsystem.module.Result;
import com.heima.homeservicemanagementsystem.openfeign.WxClient;
import com.heima.homeservicemanagementsystem.service.WxUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Description
 * @Author jcf
 * @Date 2025/3/25
 */
@Slf4j
@Tag(name = "微信登录相关")
@RestControllerMapping("/wx")
public class MiniController {
    @Resource
    private WxConstants wxConstants;
    @Resource
    private WxClient wxClient;
    @Resource
    private WxUserService wxUserService;

    @SaIgnore

    @PostMapping("/login")
    @Operation(summary = "微信登录")
    public Result login(@RequestBody String code) throws JsonProcessingException {
//        log.info("code:{}", code);
//        log.info("AppID:{}", wxConstants.getAppID());
//        log.info("AppKEY:{}", wxConstants.getAppKEY());
        String authorizationCode = wxClient.getSessionKey(wxConstants.getAppID(), wxConstants.getAppKEY(), code, "authorization_code");
        log.info("authorizationCode:{}", authorizationCode);
        ObjectMapper mapper = new ObjectMapper();
        WxRTVO wxRTVO = mapper.readValue(authorizationCode, WxRTVO.class);
        boolean openid = wxUserService.exists(new QueryWrapper<WxUser>().eq("openid", wxRTVO.getOpenid()));
        WxUser one = null;
        if (openid) {
            one = wxUserService.getOne(Wrappers.<WxUser>lambdaQuery().eq(WxUser::getOpenid, wxRTVO.getOpenid()));
            if (Objects.nonNull(one)) {
//                one.getId();
                WxUser wxUser = new WxUser();
                wxUser.setId(one.getId());
                wxUser.setSex(2);
                wxUser.setStatus(0);
                wxUser.setOpenid(wxRTVO.getOpenid());
                wxUser.setSessionKey(wxRTVO.getSession_key());
                boolean b = wxUserService.updateById(wxUser);
                if (b) {
                    Map<String, String> map = getStringMap(wxUser);
                    return Result.success("更新成功", map);
//                    return Result.success("更新成功");

                }
                return Result.error("更新失败");
            }
        } else {
            WxUser wxUser = new WxUser();
            wxUser.setOpenid(wxRTVO.getOpenid());
            wxUser.setSessionKey(wxRTVO.getSession_key());
            wxUser.setSex(2);
            wxUser.setStatus(0);
//            wxUser.setAvatar("/static/defalutimg.png");
            wxUser.setUsername("默认名字");
            boolean save = wxUserService.save(wxUser);
            if (save) {
                Map<String, String> map = getStringMap(wxUser);
                return Result.success("更新成功1", map);
            }
            return Result.error("更新失败1");
        }
        return Result.success();
    }

    @SaIgnore
    @GetMapping("/logout")
    @Operation(summary = "微信退出登录")
    public Result<Boolean> logout() {
        StpUtil.logout();
        return Result.success();
    }

    private static Map<String, String> getStringMap(WxUser wxUser) {
        StpUtil.login(wxUser.getId(), "mini");
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        Map<String, String> map = new HashMap<>(2);
        map.put("tokenHead", tokenInfo.tokenName);
        map.put("token", tokenInfo.tokenValue);
//        map.put("token", tokenInfo.tokenValue);
        return map;
    }
}
